package com.qingcloud.base.utils;

import cn.hutool.core.util.StrUtil;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.feign.UserService;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LoginUtils {
    /**
     * 慎重使用，-----》IsFull 参数暂时无效，待优化，暂时无法设定所有用户信息（使用时务必注意，需要通过id或username 获取用户详情）   TODO
     *
     * @param request
     * @param isFull
     * @return
     */
    public static LoginUserDTO getCurrentUser(HttpServletRequest request, boolean isFull) {
        LoginUserDTO loginUserDTO = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getDetails();
            //客户端模式只返回一个clientId
            if (principal instanceof LoginUserDTO) {
                loginUserDTO = (LoginUserDTO) principal;
            }
        }
        String cookieId = CookieUtil.getUserId(request);
        if (isFull && StrUtil.isNotBlank(cookieId)) {
            UserService userService = SpringUtils.getFeignBean("userService", UserService.class);
            return userService.findUserByUserId(cookieId);
        }
        if (loginUserDTO == null) {
            String userId = request.getHeader(SecurityConstants.USER_ID_HEADER);
            String username = request.getHeader(SecurityConstants.USER_HEADER);
            String fullName = request.getHeader(SecurityConstants.FULL_NAME_HEADER);
            String roles = request.getHeader(SecurityConstants.ROLE_HEADER);

            if (StrUtil.isNotBlank(userId)) {
                loginUserDTO = new LoginUserDTO();
                if (isFull) {
                    UserService userService = SpringUtils.getFeignBean("userService", UserService.class);
                    loginUserDTO = userService.findUserByName(username);
                }
                loginUserDTO.setUserId(userId);
                loginUserDTO.setUsername(username);
                loginUserDTO.setFullName(fullName);
                if (roles != null) {
                    List<String> roleList = new ArrayList<>();
                    Arrays.stream(roles.split(",")).forEach(role -> {
                        roleList.add(role);
                    });
                    loginUserDTO.setRoles(roleList);
                }
            }
        }
        return loginUserDTO;
    }

    /**
     * 慎重使用，-----》isFull 参数暂时无效，待优化，暂时无法设定所有用户信息（使用时务必注意，需要通过id或username 获取用户详情）   TODO
     *
     * @param isFull
     * @return
     */
    public static LoginUserDTO getCurrentUser(boolean isFull) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest contextRequest = requestAttributes.getRequest();
        if (contextRequest != null) {
            return LoginUtils.getCurrentUser(contextRequest, isFull);
        }
        return null;
    }
}
